#!/bin/sh

_LC_ALL="$LC_ALL"
LC_ALL=C.UTF-8;
export LC_ALL

set -e

verify_shell_is_posix_or_exit() {
  if [ -n "${ZSH_VERSION+x}" ]; then
    error "Running installation script with \`zsh\` is known to cause errors."
    error "Please use \`sh\` instead."
    exit 1
  elif [ -n "${BASH_VERSION+x}" ] && [ -z "${POSIXLY_CORRECT+x}" ]; then
    error "Running installation script with non-POSIX \`bash\` may cause errors."
    error "Please use \`sh\` instead."
    exit 1
  else
    true  # No-op: no issues detected
  fi
}

die() {
  >&2 echo "$@"
  exit 1
}

# Non-POSIX shells can break once executing code due to semantic differences
verify_shell_is_posix_or_exit

REPLACES=""
OVERWRITE=false

while [ "$#" -gt 0 ]
do
  case "$1" in
  -r|--replace)
    shift
    if [ -z "$REPLACES" ]
    then
      REPLACES="$1"
    else
      REPLACES="$REPLACES,$1"
    fi
    shift
    ;;
  -o|--overwrite)
    shift
    OVERWRITE=true
    ;;
  --)
    shift
    break
    ;;
  *)
    if echo "$1" | grep -q "^/"
    then
      PLAIN_ENVDIR="$1"
      SECRET_ENVDIR=""
      [ -d "$PLAIN_ENVDIR" ] \
        || die "$PLAIN_ENVDIR is not a directory"
    else
      SECRET_ENVDIR="${BASE_SECRET_PATH}/$1"
      PLAIN_ENVDIR="${BASE_ENV_PATH}/$1"
      [ -d "$PLAIN_ENVDIR" -o -d "$SECRET_ENVDIR" ] \
        || die "None of $PLAIN_ENVDIR or $SECRET_ENVDIR is a directory"
    fi
    shift
    for ENVDIR in "$PLAIN_ENVDIR" "$SECRET_ENVDIR"
    do
      [ -d "$ENVDIR" ] || continue
      # When md5sum of key and values of environment variables ordered alphabetically (excluding variable
      # MD5SUM_2) does not match value of variable MD5SUM_2 we fail since in transition state
      [ "$(ls -1a "$ENVDIR" | grep -v "^MD5SUM" \
        | while read ENVVAR; do [ ! -f "$ENVDIR/$ENVVAR" ] || { printf %s= "$ENVVAR"; cat "$ENVDIR/$ENVVAR"; }; done \
        | md5sum | cut -d ' ' -f 1 | tr 'a-z' 'A-Z')" = "$(cat "$ENVDIR/MD5SUM_2")" ] \
        || die "Environment variable in transient state"
      for ENVVAR in $(ls -1a "$ENVDIR")
      do
        # Only export if "$ENVDIR/$ENVVAR" is a file and name is one of a variable
        # and environment variable with name $ENVVAR is not set
        if ! {
          [ ! -f "$ENVDIR/$ENVVAR" ] \
            || ! printf %s "$ENVVAR" | grep -q '^[a-zA-Z][a-zA-Z0-9_]*$' \
            || [ "$OVERWRITE" != "true" -a -n "$(eval "echo \"\$$ENVVAR\"")" ] \
            || eval "export $ENVVAR='$(cat "$ENVDIR/$ENVVAR")'"
          }
        then
          echo "An error occurred while exporting environment variable $ENVVAR" >&2
          exit 1
        fi
      done
    done
    ;;
  esac
done

if [ -n "$REPLACES" ]
then
  for REPLACE in $(echo "$REPLACES" | tr ',' '\n')
  do
    eval "export ${REPLACE%=*}=\"\$${REPLACE#*=}\""
  done
fi

LC_ALL="$_LC_ALL"

if [ -n "$1" ]
then
  exec "$@"
fi
